package com.discuss.community.controller;

import com.discuss.community.entity.DiscussPost;
import com.discuss.community.entity.Page;
import com.discuss.community.service.DiscussService;
import com.discuss.community.service.LikeService;
import com.discuss.community.service.UserService;
import com.discuss.community.util.CommunityConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class HomeController implements CommunityConstant {
    @Autowired
    DiscussService discussService;
    @Autowired
    UserService userService;
    @Autowired
    LikeService likeService;

    @GetMapping("/index")
    public String getIndexPage(Model model, Page page) {
        page.setRows(discussService.getDiscussRows(0));
        page.setPath("/index");
        List<DiscussPost> list = discussService.getDiscussPosts(0, page.getOffset(), page.getLimit());
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if(list != null) {
            for (DiscussPost discussPost : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post",discussPost);
                map.put("user",userService.getUserByUserId(discussPost.getUserId()));
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
                map.put("likeCount", likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("page",page);
        return "/index";
    }

    @GetMapping("/error")
    public  String getErrorPage() {
        return "error/500";
    }

    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }


}
